import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:fluttercontactpicker/fluttercontactpicker.dart';
import 'package:lishopflu/base/base_import.dart';
import 'package:lishopflu/base/base_page.dart';
import 'package:lishopflu/base/controller_import.dart';
import 'package:lishopflu/base/view_import.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:lishopflu/utils/location_util.dart';
import 'package:permission_handler/permission_handler.dart';

import 'add_address_ctl.dart';

class AddAddressPage extends BasePage<AddAddressCtl>{

  @override
  void onCreate(BuildContext mContext) {
    setAppTitle('添加收货地址');
  }

  @override
  Widget pageBody(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(left: 10, right: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(
                flex: 1,
                child: Obx(() => CommonWidget.labelEdit('收货人    ', controller.nameCtl.value, hintText: '名字',maxLines: 1)),
              ),
              InkWell(
                child: Padding(
                  padding: EdgeInsets.all(10),
                  child: Text('+通讯录'),
                ),
                onTap: (){
                  isPermission();
                },
              ),
            ],
          ),
          CommonWidget.divide(),

          Row(
            children: [
              Expanded(
                flex: 1,
                child: Obx(() => CommonWidget.labelEdit('手机号码', controller.phoneCtl.value, hintText: '手机号', inputType: TextInputType.phone, maxLines: 1),),
              ),
              InkWell(
                child: Padding(
                  padding: EdgeInsets.all(10),
                  child: Row(
                    children: [
                      Obx(() => Text('+${controller.phoneCode.value}')),
                      CommonWidget.icon(),
                    ],
                  ),
                ),
                onTap: (){

                },
              ),
            ],
          ),
          CommonWidget.divide(),

          Obx(() => CommonWidget.tapText('选择地区', controller.initProvince.value+' '+controller.initCity.value+' '+controller.initTown.value, (){
            Pickers.showAddressPicker(
              context,
              initProvince: controller.initProvince.value,
              initCity: controller.initCity.value,
              initTown: controller.initTown.value,
              onConfirm: (p, c, t) {
                controller.changeProvince(p, c, t);
              },
              addAllItem: false,

            );
          }, hintText: '省、市、区'),
          ),
          CommonWidget.divide(),

          CommonWidget.tapText('详细地址','',null, showIcon: false),
          Row(
            children: [
              Expanded(
                flex: 1,
                child: Obx(() => CommonWidget.labelEdit('', controller.detailCtl.value, hintText: '小区楼栋/门牌号'),),
              ),
              InkWell(
                child: Padding(
                  padding: EdgeInsets.all(10),
                  child: Column(
                    children: [
                      CommonWidget.icon(icon: Icons.location_on, color: AppColor.accentColor),
                      Text('定位'),
                    ],
                  ),
                ),
                onTap: (){
                  myLoc();
                },
              ),
            ],
          ),
          CommonWidget.divide(),

          Row(
            children: [
              Expanded(child: Padding(child: Text('默认地址', style: TextStyle(color: AppColor.c333333),),padding: EdgeInsets.only(top: 20, bottom: 20),), flex: 1,),
              Obx(() => CupertinoSwitch(
                value: controller.isDefault.value,
                onChanged: (bool value) {
                  controller.changeDefault(value);
                },
              ),
              ),
            ],
          ),
          CommonWidget.divide(),

          Padding(padding: EdgeInsets.only(top: 30)),
          MaterialButton(
            minWidth: double.infinity,
            child: Text('保存', style: TextStyle(fontSize: 14, color: Colors.white,),),
            color: Colors.blueAccent,
            padding: EdgeInsets.only(top: 8, bottom: 8),
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
            onPressed: () {
              controller.save((data){
                if(!StringUtil.isEmpty(data)){
                  toast(data);
                  return;
                }
                LiLog.d(JsonUtil.encodeObj(controller.addressBean));
                finish();
                return;
              });
            }
          ),
        ],
      ),
    );
  }

  /// 动态申请定位权限
  void isPermission() async {
    // 申请权限
    bool hasPermission = await requestPermission();
    if (hasPermission) {
      print("读取联系人权限申请通过");
      final PhoneContact contact = await FlutterContactPicker.pickPhoneContact();
      controller.changePhone(contact);
    } else {
      print("读取联系人权限申请不通过");
    }
  }

  /// 申请定位权限
  /// 授予权限返回true， 否则返回false
  Future<bool> requestPermission() async {
    //获取当前的权限
    var status = await Permission.contacts.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.contacts.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  /*
    定位当前位置一次
   */
  void myLoc(){
    showLoading(str: '定位中...');
    LocationUtil().getLoc((Map<String, Object> map){
      hideLoading();
      LiLog.d(map);
      controller.changeLoc(map);
      return;
    });
  }
}